package com.study.redisson.util;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * 简单的包装下 RedissonClient, 仅仅为了记录日志
 */
@Component
public class RedissonUtil {

    @Resource
    private RedissonClient redissonClient;

    /**
     * 创建锁
     *
     * @param key 锁的关键字（在redis中必须唯一）
     */
    public RLock getLock(String key) {
        return redissonClient.getLock(key);
    }

    /**
     * 加锁
     *
     * @param rLock    锁对象
     * @param lockTime 锁的自动失效时间, 单位: 秒
     */
    public boolean tryLock(RLock rLock, long lockTime) {
        boolean reBoolean = false;
        try {
            reBoolean = rLock.tryLock(lockTime, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            System.out.println("加锁失败，锁：" + rLock.getName());
        }
        return reBoolean;
    }

    /**
     * 释放锁
     */
    public void unLock(RLock rLock) {
        if (null == rLock) {
            return;
        }
        String name = rLock.getName();
        try {
            rLock.unlock();
            System.out.println("释放锁成功，锁：" + name);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("释放锁失败，锁：" + (StringUtils.isEmpty(name) ? "" : name));
        }
    }
}
